package by.ostrovsky.webhousingsystem.bean.data;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import by.ostrovsky.webhousingsystem.bean.TemplateDataBean;
import by.ostrovsky.webhousingsystem.controller.IOperateController;
import by.ostrovsky.webhousingsystem.controller.employe.UpdateEmployeController;
import by.ostrovsky.webhousingsystem.controller.taskgroup.DeleteTaskGroupController;
import by.ostrovsky.webhousingsystem.controller.taskgroup.GetTaskGroupController;
import by.ostrovsky.webhousingsystem.controller.taskgroup.UpdateTaskGroupController;
import by.ostrovsky.webhousingsystem.controller.workplan.UpdateWorkplanController;
import by.ostrovsky.webhousingsystem.exception.CommonException;
import by.ostrovsky.webhousingsystem.exception.EmptyParameterException;
import by.ostrovsky.webhousingsystem.exception.OperationErrorException;
import by.ostrovsky.webhousingsystem.hibernate.entity.Employee;
import by.ostrovsky.webhousingsystem.hibernate.entity.TaskGroup;
import by.ostrovsky.webhousingsystem.hibernate.entity.WorkPlan;

@SuppressWarnings("serial")
public class TaskGroupBean extends TemplateDataBean<TaskGroup> {
	private static Logger logger = Logger.getLogger(TaskGroupBean.class);

	private String[] isBusy = null;
	private String[] freeAt = null;

	private void initSelectedEntitiesList() throws OperationErrorException {
		TaskGroup tg = new TaskGroup();
		try {
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date date = null;
			if (freeAt[Integer.parseInt(selectedEllements[0])] != "")
				date = dateFormat.parse(freeAt[Integer
						.parseInt(selectedEllements[0])]);
			boolean isBusyBoolean = Boolean.parseBoolean(isBusy[Integer
					.parseInt(selectedEllements[0])]);

			tg.setId(selectedEntities.get(0).getId());
			tg.setFreeAt(date);
			tg.setIsBusy(isBusyBoolean);
			tg.setAppointment(selectedEntities.get(0).getAppointment());

			selectedEntities = new LinkedList<TaskGroup>();
			selectedEntities.add(tg);
		} catch (Exception e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	public TaskGroupBean() {
		try {
			read();
		} catch (CommonException e) {
			logger.error(e);
		}
	}

	@Override
	public void delete() throws CommonException {
		initSelected();

		if (selectedEntities.isEmpty())
			throw new EmptyParameterException();

		IOperateController<Employee, Boolean> emController = new UpdateEmployeController();
		IOperateController<WorkPlan, Boolean> wpController = new UpdateWorkplanController();
		IOperateController<TaskGroup, Boolean> tgController = new DeleteTaskGroupController();

		EmployeBean emBean = new EmployeBean();
		WorkPlanBean wpBean = new WorkPlanBean();

		List<Employee> emList = emBean.getEntityList();
		List<WorkPlan> wpList = wpBean.getEntityList();
		List<Employee> emTmpList = new LinkedList<Employee>();
		List<WorkPlan> wpTmpList = new LinkedList<WorkPlan>();

		try {
			for (TaskGroup tg : selectedEntities) {
				for (Employee empl : emList) {
					if (empl.getTaskGroup() != null)
						if (empl.getTaskGroup().getId().equals(tg.getId())) {
							empl.setTaskGroup(null);
							emTmpList.add(empl);
						}
				}
				for (WorkPlan wp : wpList) {
					if (wp.getTaskGroup() != null)
						if (wp.getTaskGroup().getId().equals(tg.getId())) {
							wp.setTaskGroup(null);
							wpTmpList.add(wp);
						}
				}
			}

			// need to do this very carefully
			emController.set(emTmpList);
			wpController.set(wpTmpList);
			tgController.delete(selectedEntities);
		} catch (Exception e) {
			logger.error(e);
		}
		// update local copy
		read();
		try {
			sessionMap.put("reloadPrevContent", "taskgroup");
			sessionMap.put("taskgroupBean", TaskGroupBean.this);
			String source = ServletActionContext.getRequest().getHeader(
					"REFERER");
			ServletActionContext.getResponse().sendRedirect(source);
		} catch (IOException e) {
			logger.error(e);
		}
	}

	@Override
	public void update() throws CommonException {
		initSelected();
		if (selectedEllements == null)
			throw new EmptyParameterException();
		initSelectedEntitiesList();
		if (selectedEntities.isEmpty())
			throw new EmptyParameterException();
		IOperateController<TaskGroup, Boolean> controller = new UpdateTaskGroupController();
		controller.set(selectedEntities);
		read();
		try {
			sessionMap.put("reloadPrevContent", "taskgroup");
			sessionMap.remove("taskgroupBean");
			String source = ServletActionContext.getRequest().getHeader(
					"REFERER");
			ServletActionContext.getResponse().sendRedirect(source);
		} catch (IOException e) {
			logger.error(e);
		}
	}

	@Override
	public void read() throws CommonException {
		entityList = new LinkedList<TaskGroup>();
		IOperateController<TaskGroup, Boolean> controller = new GetTaskGroupController();
		entityList.addAll((List<TaskGroup>) controller.get());
	}

	public TaskGroup initTaskGroup(HousingRequestBean hrBean,
			TaskGroupBean tgBean) throws EmptyParameterException {
		try {
			List<TaskGroup> tgList = tgBean.getEntityList();
			int lastIndex = tgList.size() - 1;

			Long tgId = tgList.get(lastIndex).getId() + 1;

			long requestID = hrBean.getSelectedEntities().get(0).getId();
			String tgAppointment = hrBean.getEntityList()
					.get((int) requestID - 1).getWork();
			Date tgDate = hrBean.getEntityList().get((int) requestID - 1)
					.getDeadline();

			TaskGroup tg = new TaskGroup();
			tg.setId(tgId);
			tg.setFreeAt(tgDate);
			tg.setAppointment(tgAppointment);
			tg.setIsBusy(true);

			return tg;
		} catch (Exception e) {
			logger.error(e);
			return null;
		}
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public String[] getIsBusy() {
		return isBusy;
	}

	public void setIsBusy(String[] isBusy) {
		this.isBusy = isBusy;
	}

	public String[] getFreeAt() {
		return freeAt;
	}

	public void setFreeAt(String[] freeAt) {
		this.freeAt = freeAt;
	}

}
